const {
	add,
	del,
	edit,
	search,
	searchBy
} = require('../js/mysql.js');
const jwt = require("jsonwebtoken")

const router = require('koa-router')()



router.prefix('/users')
//登录
router.post('/login', async function (ctx, next) {
	let { body } = ctx.request;
	let { password, iphone } = body;
	let data = await searchBy(`iphone=${iphone} and password=${password}`);
	if (data.length) {
		let token = jwt.sign(body, "jiaxiaoqiong",{expiresIn: '24h'});
		ctx.body = {
			msg: '登录成功',
			code: 200,
			token,
		}
	} else {
		ctx.body = {
			msg: '用户名或密码校验失败',
			code: 511
		}
	}


})

// 创建账号
router.post('/register', async function (ctx, next) {
	let { body } = ctx.request;
	// 解构得到初始的账号密码
	let { password, iphone } = body;
	// 查询用户名是否存在
	let data = await searchBy(`iphone='${iphone}'`);
	console.log(data);
	// 如果存在，代表用户名重复
	if (data.length) {
		ctx.body = {
			msg: '用户名存在',
			code: 510
		}
	} else {
		// 存入数据库
		let data = await add([password, iphone], `user(password,iphone) VALUES(?,?)`);
		ctx.body = {
			msg: '注册成功',
			code: 200,
			data: {
				token: 'qqqqq',
				// 账户名
				iphone,
				// 角色类型
				type: 2
			}
		}
	}
})

module.exports = router
